<template>
	<view>
		<view class="gl-header">
			<view class="gl-header-left" style="gap: 10px; flex-wrap: wrap;">
				<!--
				<uni-search-bar v-model="search" placeholder="关键字搜索" cancelButton="none"
					@confirm="refresh"></uni-search-bar>
				-->
			</view>
			<view class="gl-header-right">
				<!--
				<view class="gl-button gl-button-base" hover-class="button-base-hover" :hover-stay-time="100"
					@click="refresh">
					<uni-icons type="reload" size="18" color="#fff"></uni-icons>
					<text style="font-size: small;">刷新</text>
				</view>
				-->
			</view>
		</view>
		<view class="gl-body" style="display: flex;align-items: flex-start;gap: 10px;">

			<uni-card title="业务群组" thumbnail="" extra="额外信息" note="Tips" style="width: 200px;">
				<template v-slot:title>
					<view
						style="display: flex;justify-content: space-between;padding: 10px 0;border-bottom: 1px solid #aaa;align-items: center;">
						<view style="font-weight: bold;">业务群组</view>
						<view class="" style="display: flex;align-items: center;gap: 5px;">
							<view class="gl-button gl-button-success" hover-class="button-success-hover"
								:hover-stay-time="100" @click="eventCreate">
								<uni-icons type="compose" size="18" color="#fff"></uni-icons>
								<text style="font-size: small;">创建</text>
							</view>
							<view class="gl-button gl-button-warning" hover-class="button-warning-hover"
								:hover-stay-time="100" @click="eventAddStaff">
								<uni-icons type="personadd" size="18" color="#fff"></uni-icons>
								<text style="font-size: small;">加入</text>
							</view>
							<view class="gl-button gl-button-base" hover-class="button-base-hover"
								:hover-stay-time="100" @click="loadDefData">
								<uni-icons type="reload" size="18" color="#fff"></uni-icons>
								<text style="font-size: small;">刷新</text>
							</view>
						</view>
					</view>
				</template>
				<scroll-view class="gl-body-scroll" scroll-y :style="{height:swiperH+'px'}">
					<view style="display: flex;gap: 25px;">
						<view class="">
							<checkbox-group @change="checkboxChange">
								<template v-for="(item,index) in depTree" :key="index">
									<view v-if="item.parentid === 0" class="dep-name-block">
										<view class="dep-name-item">
											<uni-icons type="right" size="24"></uni-icons>
											<view class="dep-name-card"><text>{{item.name}}</text></view>
										</view>
										<view class="" style="padding-left: 25px;">
											<view v-for="(user, indexu) in item.child" :key="indexu"
												class="dep-name-user">
												<checkbox :value="user.userid" style="transform:scale(0.7)"
													:checked="curCheckBox.includes(user.userid)" />
												<uni-icons type="contact" size="24"></uni-icons>
												<view class=""><text>{{user.name}}</text></view>
											</view>
										</view>
										<template v-for="(child,cindex) in depTree" :key="cindex">
											<view v-if="child.parentid === item.id" class="dep-name-block"
												style="padding-left: 25px;">
												<view class="dep-name-item">
													<uni-icons type="down" size="24"></uni-icons>
													<view class="dep-name-card"><text>{{child.name}}</text></view>
												</view>
												<view class="" style="padding-left: 25px;">
													<view v-for="(user, indexu) in child.child" :key="indexu"
														class="dep-name-user">
														<checkbox :value="user.userid" style="transform:scale(0.7)"
															:checked="curCheckBox.includes(user.userid)" />
														<uni-icons type="contact" size="24"></uni-icons>
														<view class=""><text>{{user.name}}</text></view>
													</view>
												</view>
											</view>
										</template>
									</view>
								</template>
							</checkbox-group>
						</view>
						<view class="">
							<uni-section class="mb-10" v-for="(chat, index) in chatList" :key="index" :title="chat.name"
								:sub-title="chat.chatid" type="line"
								style="background-color: #f1f1f1;padding: 15px;border-radius: 10px;">
								<template v-slot:default>
									<view style="padding: 0 20px;">
										<view
											style="padding: 10px 0;display: flex;justify-content: space-between;align-items: center;">
											<view class="">
												<text>群主:</text><text
													style="font-weight: bold;">{{ filterStaff(chat.chat_info.owner).name }}</text>
											</view>
											<view style="display: flex;align-items: center;gap: 10px;">
												<uni-data-select v-model="chat.mode" :localdata="mailMode"
													emptyTips="分配群组消息功能" label="消息功能"
													@change="(e)=>{mailChange(chat.id, e)}"></uni-data-select>
												<view class="gl-button gl-button-warning"
													hover-class="button-warning-hover" :hover-stay-time="100"
													@click="eventMessage(chat.chatid)">
													<uni-icons type="chat" size="18" color="#fff"></uni-icons>
													<text style="font-size: small;">发送应用消息</text>
												</view>
											</view>
										</view>
										<view style="display: flex;flex-wrap: wrap;gap: 10px;">
											<view v-for="user in chat.chat_info.userlist" class="chat-staff-card">
												<text style="padding-right: 10px;">{{filterStaff(user).name}}</text>
												<uni-icons type="more" size="16"
													@click="staffActChange(chat.chatid, user)"></uni-icons>
											</view>
										</view>
									</view>
								</template>
								<template v-slot:right>
									{{chat.lasttime}}
								</template>
							</uni-section>
						</view>
						<view class="">
							<text style="font-weight: bold;">消息功能模板</text>
							<uni-section class="mb-10" v-for="(mail, index) in mailData" :key="index" :title="mail.name"
								:sub-title="mail.url" type="line">
								<template v-slot:right>
									<view class="" style="display: flex;justify-content: flex-end;">
										<view style="width: 60px;">
										</view>
										<text class="gl-link gl-link-base" @click="eventUpdateMail(mail)">编辑</text>
									</view>
								</template>
							</uni-section>
						</view>
					</view>
				</scroll-view>
			</uni-card>


		</view>
		<view class="gl-footer">

		</view>

		<!--模态窗口-->
		<popQywxInfoVue ref="popQywxInfo" @refresh="loadDefData"></popQywxInfoVue>
		<!--模态按钮组-->
		<popDialogMultipleVue ref="popDialogMultiple" title="编辑群聊" :vertical="false" :action="actionData"
			@master="popConfirm" @remove="popClose" @close="()=>{this.$refs.popDialogMultiple.close()}">
		</popDialogMultipleVue>
		<!--模态mail-->
		<popQywxMailVue ref="popQywxMail" @refresh="loadDefData"></popQywxMailVue>
	</view>
</template>

<script>
	import psMethod from '@/common/psMethod';
	import popQywxInfoVue from './pop-qywx-info.vue';
	import popDialogMultipleVue from '@/components/pop-dialog-multiple/pop-dialog-multiple.vue';
	import popQywxMailVue from './pop-qywx-mail.vue';
	export default {
		data() {
			return {
				swiperH: 0,
				sConf: getApp().globalData,
				search: '',
				depTree: [], // 架构树
				staffData: [], // 所有员工
				chatList: [], // 群列表
				curCheckBox: [], // 勾选的员工
				curStaff: {
					depid: null,
					userid: null
				},
				actionData: [{
					text: '提升群主',
					icon: 'staff',
					value: 'master',
					bgColor: '#f1f1f1',
					txtColor: "#007aff"
				}, {
					text: '移除群组',
					icon: 'trash',
					value: 'remove',
					bgColor: '#f1f1f1',
					txtColor: "#dd524d"
				}, {
					text: '取消',
					icon: 'redo',
					value: 'close',
					bgColor: '#f1f1f1',
					txtColor: "#f0ad4e"
				}],
				mailMode: [], // 转换后的的select对象
				mailData: [], // 原始对象
			}
		},
		mounted() {
			console.log('页面挂载');
			let window = uni.getWindowInfo();
			this.designLayout(window.windowHeight);
			this.loadDefData()
		},
		components: {
			popQywxInfoVue,
			popQywxMailVue,
			popDialogMultipleVue
		},
		methods: {
			designLayout(wh) {
				this.$nextTick(() => {
					const query = uni.createSelectorQuery().in(this);
					query.select('.gl-body-scroll').boundingClientRect();
					query.select('.gl-footer').boundingClientRect();
					query.exec((res) => {
						this.swiperH = wh - Math.ceil(res[0].top) - Math.ceil(res[1].height) - 30;
					});
				})
			},
			async loadDefData() {
				await this.loadWxChatMail().then(res => {
					console.log('加载群组消息类目', res);
					let tmpData = []
					res.resmsg.forEach(item => {
						tmpData.push({
							value: item.id,
							text: item.name
						})
					})
					this.mailMode = tmpData
					this.mailData = res.resmsg
				})
				await this.loadDepartmentTree().then(res => {
					console.log('加载企业架构树', res);
					this.depTree = res.resmsg
					let tmpData = []
					this.depTree.forEach(item => {
						tmpData.push(...item.child)
					})
					this.staffData = tmpData
				})

				await this.loadWxChatList().then(res => {
					console.log('加载业务群列表', res);
					this.chatList = res.resmsg
				})
			},
			/**
			 * 发送应用消息
			 */
			eventMessage(e) {
				console.log('eventMessage');
				let that = this
				uni.showModal({
					title: '发送应用消息',
					placeholderText: '消息文本, 支持class=highlight, gray, normal',
					editable: true,
					success(r) {
						if (r.confirm) {
							if (!r.content) {
								uni.showToast({
									title: '消息无效'
								})
								return
							} else {
								let data = {
									chatid: e,
									title: '系统消息',
									description: r.content,
									url: 'https:///',
									btntxt: '详情'
								}
								that.loadWxChatSend(data)
							}
						}
					}
				})
			},
			eventUpdateMail(e) {
				console.log('eventUpdateMail', e);
				this.$refs.popQywxMail.open(e)
			},
			/**
			 * 修改群功能			
			 */
			mailChange(chatid, e) {
				console.log('mailChange', chatid, e);
				if (e) {
					let that = this
					uni.showModal({
						title: '询问',
						content: "是否要修改群功能",
						success(r) {
							if (r.confirm) {
								let data = {
									gid: chatid,
									eid: e
								}
								that.loadwxChatMailUp(data).then(res => {
									that.loadDefData()
								}).catch(err => {
									uni.showToast({
										title: '失败了'
									})
								})
							}
						}
					})
				}
			},
			addstaffToChatid(e) {
				console.log('addstaffToChatid', e);
				let depid = this.chatList[e].chatid
				console.log(depid);
				let data = {
					chatid: depid,
					add_user_list: this.curCheckBox
				}
				this.loadWxChatUpdate(data).then(res => {
					console.log('添加成员', res);
					this.loadDefData()
				}).catch(err => {
					uni.showToast({
						title: '失败了'
					})
				})
			},
			popConfirm() {
				console.log('popConfirm', this.curStaff);
				let data = {
					chatid: this.curStaff.depid,
					owner: this.curStaff.userid
				}
				this.loadWxChatUpdate(data).then(res => {
					console.log('提升群主', res);
					this.loadDefData()
				}).catch(err => {
					uni.showToast({
						title: '失败了'
					})
				}).finally(() => {
					this.$refs.popDialogMultiple.close()
				})
			},
			popClose() {
				console.log('popClose', this.curStaff);
				let data = {
					chatid: this.curStaff.depid,
					del_user_list: [this.curStaff.userid, ]
				}
				this.loadWxChatUpdate(data).then(res => {
					console.log('移除用户', res);
					this.loadDefData()
				}).catch(err => {
					console.log('移除用户__失败', err);
					uni.showToast({
						title: '失败了'
					})
				}).finally(() => {
					this.$refs.popDialogMultiple.close()
				})
			},
			eventAddStaff() {
				console.log('eventAddStaff');
				if (this.curCheckBox.length < 1) {
					uni.showModal({
						title: '错误',
						content: '加入群组至少需要1名成员',
						showCancel: false
					})
					return
				}
				console.log('eventAddStaff', this.curCheckBox);

				let tmpData = []
				this.chatList.forEach(item => {
					tmpData.push(item.name)
				})
				if (tmpData.length < 1) {
					this.eventCreate()
				}
				let that = this
				uni.showActionSheet({
					title: '选择目标群组',
					itemList: tmpData,
					success(r) {
						console.log('选中了->', r);
						that.addstaffToChatid(r.tapIndex)
					}
				})
			},
			staffActChange(e, s) {
				console.log('staffActChange', e, s);
				this.curStaff = {
					depid: e,
					userid: s
				}
				this.$refs.popDialogMultiple.open()
			},
			checkboxChange(e) {
				console.log('checkboxChange', e.detail.value);
				this.curCheckBox = e.detail.value
			},
			eventCreate() {
				console.log('eventCreate');
				if (this.curCheckBox.length < 2) {
					uni.showModal({
						title: '错误',
						content: '创建群组至少需要2名成员',
						showCancel: false
					})
					return
				}
				let tmpData = []
				this.curCheckBox.forEach(item => {
					tmpData.push(this.staffData.find(staff => staff.userid === item))
				})
				this.$refs.popQywxInfo.open(tmpData)
			},
			filterDepTree(e) {
				return this.depTree.find(item => item.parentid === e)
			},
			filterStaff(e) {
				return this.staffData.find(item => item.userid === e)
			},
			loadWxChatList() {
				let host = this.sConf.host + '/admin/chatList/';
				let token = this.sConf.auth.token || '';
				let data = {}
				return new Promise((resolve, reject) => {
					psMethod.authenticatorGetSync(host, token, data).then(res => {
						resolve(res)
					}).catch(err => {
						reject(err)
					})
				})
			},
			loadWxChatUpdate(e) {
				let host = this.sConf.host + '/admin/chatUpdate/';
				let token = this.sConf.auth.token || '';
				return new Promise((resolve, reject) => {
					psMethod.authenticatorPostSync(host, token, e).then(res => {
						resolve(res)
					}).catch(err => {
						reject(err)
					})
				})
			},
			loadWxChatSend(e) {
				let host = this.sConf.host + '/admin/chatSend/';
				let token = this.sConf.auth.token || '';
				return new Promise((resolve, reject) => {
					psMethod.authenticatorPostSync(host, token, e).then(res => {
						resolve(res)
					}).catch(err => {
						reject(err)
					})
				})
			},
			loadDepartmentTree() {
				let host = this.sConf.host + '/admin/userTree/';
				let token = this.sConf.auth.token || '';
				let data = {}
				return new Promise((resolve, reject) => {
					psMethod.authenticatorPostSync(host, token, data).then(res => {
						resolve(res)
					}).catch(err => {
						reject(err)
					})
				})
			},
			loadWxChatMail() {
				let host = this.sConf.host + '/admin/chatMail/';
				let token = this.sConf.auth.token || '';
				let data = {}
				return new Promise((resolve, reject) => {
					psMethod.authenticatorGetSync(host, token, data).then(res => {
						resolve(res)
					}).catch(err => {
						reject(err)
					})
				})
			},
			loadwxChatMailUp(e) {
				let host = this.sConf.host + '/admin/mailUpdate/';
				let token = this.sConf.auth.token || '';
				return new Promise((resolve, reject) => {
					psMethod.authenticatorPostSync(host, token, e).then(res => {
						resolve(res)
					}).catch(err => {
						reject(err)
					})
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.dep-name-block {
		display: flex;
		flex-direction: column;
		gap: 5px;
	}

	.dep-name-item {
		display: flex;
		align-items: center;
		gap: 5px;
	}

	.dep-name-user {
		display: flex;
		gap: 5px;
	}

	.dep-name-card {
		font-weight: bold;
	}

	.chat-staff-card {
		padding: 5px 10px;
		border: 1px solid #aaa;
		border-radius: 5px;
		display: flex;
		gap: 5px;
	}
</style>